package com.leetcode.algorithm.y22.m09.w4;

/**
 * 1700. 无法吃午餐的学生数量
 * 
 * https://leetcode.cn/problems/number-of-students-unable-to-eat-lunch/
 * 
 * @author jie.deng
 *
 */
class Question1700Solution02 {

	public int countStudents(int[] students, int[] sandwiches) {
		// arr[0]表示喜欢圆形三明治的学生数量
		// arr[1]表示喜欢方形三明治的学生数量
		int[] arr = new int[2];
		int len = students.length;
		for (int i = 0; i < len; i++) {
			arr[students[i]]++;
		}

		if (arr[0] == 0) {
			int idx = 0;
			while (idx < len && sandwiches[idx] == 1) {
				idx++;
			}
			return len - idx;
		} else if (arr[1] == 0) {
			int idx = 0;
			while (idx < len && sandwiches[idx] == 0) {
				idx++;
			}
			return len - idx;
		}
		for (int i = 0; i < len; i++) {
			int num = sandwiches[i];
			arr[num]--;
			if (arr[num] == 0) {
				// 剩下的学生只喜欢某一种三明治
				int idx = i + 1;
				while (idx < len && sandwiches[idx] == (num ^ 1)) {
					idx++;
				}
				return len - idx;
			}
		}
		return 0;
	}

}